package com.study.system.edugatewayservice.filter;

import com.edu.common.entity.User;
import com.edu.common.util.JwtUtils;
import com.edu.common.util.RsaUtils;
import com.study.system.edugatewayservice.config.WhiteListConfig;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局令牌过滤器
 */
@Component
public class GlobalTokenValidateFilter implements GlobalFilter, Ordered {

    private Logger logger = LoggerFactory.getLogger(GlobalTokenValidateFilter.class);

    @Resource
    private WhiteListConfig whiteListConfig;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //请求url是白名单，就直接放行
        for(Object url : whiteListConfig.getWhiteList()){
            if(request.getURI().toString().contains(url.toString())){
                logger.info("白名单直接放行：{}",request.getURI());
                return chain.filter(exchange);
            }
        }
        //获得请求头中的token
        String token = request.getHeaders().getFirst("Authorization");
        if(token == null){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            DataBuffer data = response.bufferFactory().wrap("令牌为空".getBytes());
            return response.writeWith(Mono.just(data));
        }
        //解析token
        try {
            User user = JwtUtils.getUserFromToken(token, RsaUtils.publicKey);
            logger.info("网关令牌解析成功:{}",user);
            //放行请求
            return chain.filter(exchange);
        } catch (Exception e) {
            logger.error("网关令牌解析失败",e);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            DataBuffer data = response.bufferFactory().wrap("令牌解析错误".getBytes());
            return response.writeWith(Mono.just(data));
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
